const moment = require("moment");
const qr = require("qr-image");
import config from "../config";
// const fetch = require('node-fetch');
const axios = require("axios");
const Api = {
  path: config.webhooks,
};
// > installUrl: <font color=\"blue\">${version.installUrl}</font>
const markdown = (app, version, branch, filename) => {
  const currentTime = moment(new Date()).format("YYYY-MM-DD hh:mm");
  return {
    msgtype: "actionCard",
    actionCard: {
      title: `${app.appName}_${version.versionStr}_mobsf上传扫描构建通知`,
      text: `#### ${app.appName}${branch ? branch : ''}上传Mobsf成功 ${branch ? '\n\n 分支：' + branch : ''}\n\n 平台：${app.platform} \n\n  版本：${version.versionStr} \n\n发布时间：${currentTime} \n\n 最近的扫描 : ${config.mobsfUrl}/recent_scans/ \n\n 当前包扫描 ：${config.mobsfUrl}/${app.platform == 'ios' ? 'static_analyzer_ios' : 'static_analyzer'}/?name=${filename}&checksum=${version.md5}&type=${app.platform == 'ios' ? 'ipa' : 'apk'}`,
      // btnOrientation: "0",
      // btns: [
      //   {
      //     title: "最近的扫描",
      //     actionURL: `http://116.62.196.25:9080/recent_scans/`,
      //   },
      //   {
      //     title: "当前结果",
      //     actionURL: `http://116.62.196.25:9080/static_analyzer/?name=${filename}&checksum=${version.md5}&type=${app.platform == 'ios' ? 'ipa' : 'apk'}`
      //   },
      // ],
    },
  };
};

/**
 * 
 * @param {xapk, apk, apks, zip, ipa, or appx} scan_type  
 * @param {Name of the app with extension} file_name 
 * @param {hash of the scan} hash 
 * @param {0 or 1, default is 0} re_scan 
 * @returns 
 */
const mobsfScan = (scan_type, file_name, hash, re_scan) => {
  return axios.request({
    url: `http://${mobsfUrl}/api/v1/scan`,
    data: {
      scan_type: scan_type,
      file_name: file_name,
      hash: hash,
      re_scan: re_scan
    },
    method: "post",
    headers: {
      "Content-Type": "application/json",
      "Authorization": config.mobsfAuth
    },
  });
};
const lan = async (app, version, branch, filename) => {
  const promises = Api.path.map((item) => {
    const markdownJson = markdown(app, version, branch, filename);
    return axios.request({
      url: `${item.host}${item.path}${item.access_token}`,
      data: markdownJson,
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
    });
  });
  for (const p of promises) {
    const data = await p;
    console.log(data);
  }
};
/**
 * 
 * @param {*} app 
 * @param {*} version 
 * @param {*} branch 
 * @param {*} filename 
 */
const mobsfPush = (app, version, branch, filename) => {
  lan(app, version, branch, filename);
};

module.exports = { mobsfPush, mobsfScan };
